package com.manlitech.cloudboot.config.httpaopconfig;

import com.manlitech.cloudboot.common.constant.LogAndAuthConstant;
import org.apache.dubbo.rpc.RpcContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 拦截Action请求
 * @author Shensg
 * 2018年5月31日
 */
@Aspect
@Component
public class HttpAspect {

    @Value("${dubbo.enable}")
    private boolean dubboEnable;

	private Logger logger = LoggerFactory.getLogger(HttpAspect.class);
	  
    ThreadLocal<Long> startTime = new ThreadLocal<>();
  
    @Pointcut("execution(* com.manlitech.cloudboot..*.controller..*Controller.*(..))")
    public void webLog(){}  
  
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());  
  
        // 接收到请求，记录请求内容  
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 设置traceid
        MDC.put(LogAndAuthConstant.TRACEID , request.getHeader(LogAndAuthConstant.TRACEID));
        // 判断是否启用dubbo 并设置相关信息
        if(dubboEnable){
            RpcContext.getContext().setRequest(request);
            RpcContext.getContext().setAttachment(LogAndAuthConstant.TOKEN,request.getHeader(LogAndAuthConstant.TOKEN));
            RpcContext.getContext().setAttachment(LogAndAuthConstant.TRACEID , request.getHeader(LogAndAuthConstant.TRACEID));
        }
    }

  
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

    }

    @AfterThrowing(pointcut = "webLog()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint, Exception ex) {
        String ret = null;

    }

    public String getExceptionToString(Throwable e) {
        if (e == null){
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
}
